<template>
  <div class="page-wrap packetAnalysis">
    <!-- <div style="color: rgb(27, 76, 184); margin-bottom: 15px">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnCompanyList"> 实网演练 </span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="cursor: pointer" @click="returnCompany">
        {{ this.$route.query.name }}
      </span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">数据包分析</span>
    </div> -->
    <div
      class="page-content"
      :style="{
        height: contentHei === 'auto' ? contentHei : `${contentHei}px`,
      }"
    >
      <div class="img-header">
        <Button
          style="margin-right: 15px"
          type="primary"
          ghost
          @click="returnCompany"
        >
          <Icon type="md-arrow-back" />
          返回
        </Button>
        <div style="font-weight: 700; font-size: 18px">数据包分析</div>
      </div>
      <div class="content-wrap">
        <Row>
          <Col span="6" v-if="false">
            <div class="targetHeader_left">
              <Tree :data="treeData"></Tree>
            </div>
          </Col>
          <Col span="24">
            <div class="targetHeader">
              <Dropdown
                trigger="click"
                @on-click="downloadItem"
                style="margin-right: 10px"
              >
                <Button
                  type="info"
                  shape="circle"
                  :disabled="queryParams.Dates.length == 0"
                >
                  <Icon type="ios-cloud-download-outline" size="14" />
                  下载数据包
                </Button>
                <template #list>
                  <DropdownMenu>
                    <DropdownItem name="pcap">PCAP</DropdownItem>
                    <DropdownItem name="pcapng">PCAPNG</DropdownItem>
                  </DropdownMenu>
                </template>
              </Dropdown>
              <Button
                type="primary"
                ghost
                shape="circle"
                style="margin-right: 10px"
                @click="toLineAnalysis"
              >
                <Icon type="ios-folder-outline" size="14" />
                在线分析
              </Button>

              <DatePicker
                :editable="false"
                type="datetimerange"
                :value="queryParams.Dates"
                format="yyyy-MM-dd HH:mm:ss"
                placement="bottom-start"
                confirm
                ref="datePicker"
                placeholder="选择日期"
                transfer
                style="width: 249px; margin-right: 10px"
                @on-ok="clickOkBtn"
                @on-clear="clickClearBtn"
                @on-change="changeDates"
              ></DatePicker>
              <!-- <Select filterable
                style="width: 150px; margin-right: 10px"
                v-model="queryParams.condition"
                placeholder="过滤条件"
                filterable
                clearable
                transfer
                @on-change="changeTarget"
              >
                <Option value="IPV4">源IPV4</Option>
              </Select> -->

              <Select filterable
                v-model="queryParams.key"
                placeholder="请选择字段"
                clearable
                style="width: 150px; margin-right: 0px"
                class="condition_radius"
              >
                <!-- <Option v-for="item in queryObj" :value="item" :key="item">
                  {{ item }}
                </Option> -->
                <Option
                  v-for="(item, index) in sessionData"
                  :value="item.dto || item.key"
                  :key="index"
                  @click.native="getMoreParams(item)"
                  >{{ item.value }}</Option
                >
              </Select>
              <Select filterable
                v-model="queryParams.condition"
                placeholder=""
                class="condition_radius"
                style="width: 90px; margin-right: 0px"
              >
                <Option
                  v-for="(value, key, index) in conditionItem"
                  :key="index"
                  :value="key"
                  >{{ value }}</Option
                >
              </Select>
              <Select filterable
                v-if="selectType == 'select'"
                v-model="queryParams.selectValue"
                placeholder=""
                clearable
                class="condition_radius"
                style="width: 150px; margin-right: 0px"
              >
                <Option
                  v-for="(item, index) in sessionSelectValue"
                  :value="item.value"
                  :key="item.id || index"
                  >{{ item.value }}</Option
                >
                <!-- <Option value="port">接口名称</Option>
                <Option value="IPV4">源IPV4</Option>
                <Option value="IPV6">源IPV6</Option>
                <Option value="name">名称</Option> -->
              </Select>
              <Input
                v-else
                v-model.trim="queryParams.value"
                placeholder=""
                clearable
                class="input_value"
                style="width: 150px; margin-right: 0px"
              ></Input>
              <Button
                type="info"
                :disabled="
                  !(queryParams.value || queryParams.selectValue) &&
                  !queryParams.key
                "
                style="height: 32px; border-radius: unset; margin-right: 10px"
                @click="addQueryParams"
              >
                <Icon type="ios-add" size="14" />
                添加过滤
              </Button>

              <Button
                type="primary"
                ghost
                shape="circle"
                @click="refreshParams"
              >
                <Icon type="md-refresh" size="14" />
                刷新
              </Button>
            </div>
            <div style="margin-bottom: 10px" v-if="queryFiltering.length > 0">
              <Tag
                type="border"
                color="primary"
                closable
                v-for="(item, index) in queryFiltering"
                :key="index"
                @on-close="handleDeleteTag(item)"
              >
                {{
                  item.key +
                  " " +
                  conditionText(item.condition) +
                  " " +
                  item.value
                }}
              </Tag>
            </div>
            <Table :columns="packetCol" :data="packetList"></Table>
            <Page
              class="page_center"
              :total="packetTotal"
              show-total
              show-elevator
              @on-page-size-change="getTargetSize"
              :current="queryParams.pageIndex"
              @on-change="getTargetPage"
            >
            </Page>
          </Col>
        </Row>
      </div>
    </div>
    <Modal
      :value="progress.show"
      title="下载进度"
      width="500"
      :mask-closable="false"
      footer-hide
      @on-visible-change="change"
    >
      <Progress
        :percent="progress.progress"
        :stroke-width="20"
        :status="progress.status"
        text-inside
      />
    </Modal>
  </div>
</template>
<script>
import PackageProgress from '@/components/package-progress/package-progress.vue';
import { mapState } from 'vuex';
import networkBehavior from '@/view/drill_compete/page/componentHW/networkBehavior'
import threatEvent from '@/view/drill_compete/page/componentHW/threatEvent'
import trafficRetrieval from '@/view/drill_compete/page/componentHW/trafficRetrieval'
import SearchTable from '@/components/SearchTable/SearchTable';
import {flowMachlake,trafficArchivingDown,fullFlowDown,sessionDetailKey,sessionKeyValue} from '@/api/integration3d';
export default {
  name:'packetAnalysis',
  components: { PackageProgress,SearchTable},
  data () {

    return {
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      monitorDefault: 'networkBehavior',
      // 裁判禁用行为监控
      showMonitoring: false,
      progress: {
        show: false,
        progress: 0,
        status: 'active'
      },
      queryParams: {
        condition: 'eq', //条件表达式 and 或者 or 默认and ,
        Dates: [],
        endTime: '', //结束时间 ,
        startTime: '',//开始时间
        offlineTaskId: '', //离线任务Id
        pageIndex: 1,
        pageSize: 10,
        key: '',
        value: '',
        selectValue: '',
        sessionQueryConditionList: [
          // {
          //   condition: '',//条件表达式 = 和 != ,
          //   key: '', //查询条件 
          //   value: '', //值
          // }
        ],
        projectId :this.$route.query.prjid,
        // projectId: "J6c710a699fd4d83a7418c468bf5b562",
      },
      packetTotal: 0,
      packetList: [],
      packetCol: [
        {
          title: '时间',
          key: 'start_time',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          // placement: 'top-left',
          width: 120
        },
        {
          title: '源IP',
          key: 'ipv4_initiator',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: '源端口',
          key: 'port_initiator',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: '目的IP',
          key: 'ipv4_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: '目的端口',
          key: 'port_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: '传输层协议',
          key: 'ip_protocol',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: 'tcpFlags',
          key: 'tcp_established_success_flag',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // placement: 'top-left'
        },
        {
          title: 'VLANID',
          key: 'vlan_id',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '总字节数',
          key: 'total_bytes',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '应用',
          key: 'application_name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '应用层协议',
          key: 'l7_protocol',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          // fixed: 'right',

        },
        {
          title: '源MAC地址',
          key: 'l7_protocol',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,

        },
        {
          title: '目的MAC地址',
          key: 'l7_protocol',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '源IP国家',
          key: 'country_id_initiator',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '源IP省份',
          key: 'province_id_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '源IP城市',
          key: 'city_id_initiator',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '目的IP国家',
          key: 'country_id_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '目的IP省份',
          key: 'province_id_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
        {
          title: '目的IP城市',
          key: 'city_id_responder',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
        },
      ],

      // 树型数据
      treeData: [
        {
          title: 'IPV4',
          expand: true,
          children: [
            {
              title: 'IPV4 1-1-1'
            },
            {
              title: 'IPV4 1-1-2'
            }
          ]
        },
        {
          title: 'IPV6',
          expand: true,
          children: [
            {
              title: 'IPV6 1-1-1'
            },
            {
              title: 'IPV6 1-1-2'
            }
          ]
        },
        {
          title: 'port',
          expand: true,
          children: [
            {
              title: 'port 1-1-1'
            },
            {
              title: 'port 1-1-2'
            }
          ]
        }
      ],
      // 筛选值
      queryObj: {},
      // 查询字段太长了，重新定义赋值
      queryFiltering: [],
      conditionObj: {
        eq: '=',
        ne: '!=',
        lt: '<',
        le: '<=',
        gt: '>',
        ge: '>=',
        like: 'like',
        match: 'Match',
        leftLike: 'left-like',
        rightLike: 'right-like',
      },
      sessionParams: {
        // TrafficArchiving  流量归档 TrafficRetrieval 流量检索(会话详情)
        capacity:'TrafficRetrieval', 
        key:'',
        pageIndex: 1,
        pageSize: 9999
      },

      // 根据接口 key 和运算符
      sessionData: [],
      // 获取动态运算符
      conditionItem: {
        eq: '=',
        ne: '!=',
      },
      // 根据key 值获取 value  仅在有下拉情况下有内容
      sessionSelectValue: [],
      selectType:'text'

    }
  },
  computed: {
    ...mapState('board', ['newNotice'])
  },
  watch: {},
  created() {},
  async mounted() {
    this.$store.commit('addBreadItem', { name: this.$route.query.name });
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    this.sessionKeyValue()
    // this.sessionDetailKey()
    this.getFlowMachlake()
  },
  methods: {
    initQueryParams () {
      this.queryParams = {
        condition: '', //条件表达式 and 或者 or 默认and ,
        Dates: [],
        endTime: '', //结束时间 ,
        startTime: '',//开始时间
        offlineTaskId: '', //离线任务Id
        pageIndex: 1,
        pageSize: 10,
        key: '',
        value: '',
        sessionQueryConditionList: [
          // {
          //   condition: '',//条件表达式 = 和 != ,
          //   key: '', //查询条件 
          //   value: '', //值
          // }
        ],
        projectId: this.$route.query.prjid,
        // projectId: "J6c710a699fd4d83a7418c468bf5b562",
      }
      this.queryFiltering = []
    },

    refreshParams () {
      this.initQueryParams()
      this.getFlowMachlake()
    },

// 获取列表数据
    getFlowMachlake () {
      // let { startTime, endTime } = this.queryParams
      // if (
      //   new Date(endTime).getTime() -
      //   new Date(startTime).getTime() >
      //   60 * 60 * 1000
      // ) {
      //   this.$Message.error('起止时间间隔在一个小时内');
      //   return
      // }
      let params = {
        endTime: this.queryParams.endTime, //结束时间 ,
        startTime: this.queryParams.startTime,//开始时间
        projectId: this.queryParams.projectId,//开始时间
        offlineTaskId: '', //离线任务Id
        sessionQueryConditionList: this.queryParams.sessionQueryConditionList,
        pageIndex: 1,
        pageSize: 10,
      }
      if (params.sessionQueryConditionList.length == 0) {
        delete params.sessionQueryConditionList
      }
      flowMachlake(params).then(res => {
        if (res.code == 1) {
          this.packetList = res.data.items
          this.packetTotal = res.data.total
          console.log('🚀 flowMachlake ~ this.packetList:', this.packetList)
        } else {
          this.packetList = []
          this.packetTotal = 0
        }
      }).catch(error => {
        this.$message.error(error)
      })
    },


    getTargetPage (val) {
      this.queryParams.pageIndex = val
    },
    getTargetSize (size) {
       this.queryParams.pageSize = size;
    },

    // 选择时间
    clickClearBtn () {
      this.queryParams.Dates = []
      this.clickOkBtn()
    },
    changeDates (timeList) {
      console.log('hangeDates ~ timeList:', timeList)
      if (timeList[0]) {
        this.queryParams.Dates = timeList
        this.queryParams.startTime = timeList[0]
        this.queryParams.endTime = timeList[1]
      } else {
        this.queryParams.Dates = []
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },

    clickOkBtn () {
      this.getFlowMachlake()
      // this.isClickOkBtn = true
    },

    // 条件
    changeTarget (val) {
      console.log('changeTarget ~ val:', val)
    },

    //在线分析
    toLineAnalysis () {
      console.log('=====点击分析');
       this.$router.push({
        path: '/lineAnalysis',
        query: {
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page,
          sceneName:'点击分析',
        }
      });
    },

      // 
    downloadItem (val) {
      console.log('🚀 ~ file: trafficRetrieval.vue:479 ~ downloadItem ~ val:', val)
      let project = this.$route.query.prjid
      // let project = 'Jaffae2f077b417eb359a3ebda67dd37'
      let fileType = val == 'pcap' ? '0' : '2'  // 0: pcap, 2: pcapng 描述不同的文件格式。
      let data = {
        endTime: this.queryParams.endTime,
        startTime: this.queryParams.startTime,
        fileName: '', // 文件名称
        fileType: val,
        projectId: project,
        offlineTaskId: "",
        queryCondition: this.queryParams.sessionQueryConditionList,
      }
      if (data.queryCondition.length == 0) {
        delete data.queryCondition
      }
      trafficArchivingDown(data).then(res => {
        if (res.code == 1) {
          console.log('=========', res.data);
          this.downloadDrillReport(res.data, val)
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    downloadDrillReport (taskId, val) {
      let sceneId = this.$route.query.id;
      this.progress.show = true
      let flag = false // 不存在文件，进度条控制为0
      fullFlowDown(taskId, this.downFileProgress).then(res => {
        this.totalProgress = 0
        if (res.type == 'application/octet-stream') {
          const link = document.createElement("a");
          const href = window.URL.createObjectURL(res);
          link.href = href;
          link.download = `${this.$route.query.name}-数据包.${val}`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        } else {
          flag = true
          this.progress.status = 'wrong'
          this.$Message.error('下载文件失败!不存在文件数据！');
        }
      }).catch(error => {
        this.progress.status = 'wrong'
        this.$Message.error('下载失败!');
      }).finally(() => {
        if (flag) {
          this.progress.progress = 0
        } else {
          this.progress.progress = 100
        }
        setTimeout(() => {
          this.progress.show = false
          this.progress.status = 'active'
          this.progress.progress = 0
        }, 2000)

      })
    },
    // 进度
    downFileProgress (progress) {
      let currentProgress = progress.loaded * 1; //B单位
      if (this.totalProgress) {
        this.totalProgress += currentProgress
      } else {
        this.totalProgress = currentProgress
      }
      currentProgress = this.totalProgress - currentProgress ? currentProgress : currentProgress / 2;
      let rate = (((this.totalProgress - currentProgress) / this.totalProgress) * 100).toFixed(2) * 1;
      if (!this.rate || rate > this.rate) {
        this.progress.progress = rate;
      }
    },

    change (val) {
      this.progress.show = val
    },

    // 获取协议
    sessionDetailKey () {
      sessionDetailKey().then(res => {
        if (res.code == 1) {
          this.queryObj = res.data
          console.log('🚀 this.queryObj:', res.data)
        } else {
          this.queryObj = {}
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 初始化条件
    initSessionKeyValue () {
      this.queryParams.key = ''
      this.queryParams.value = ''
      this.queryParams.selectValue = ''
      this.queryParams.condition = 'eq'
      this.sessionSelectValue = []
      this.selectType = 'text'
      this.conditionItem = {
        eq: '=',
        ne: '!=',
      }
    },

    addQueryParams () {
      if (!this.queryParams.key || !(this.queryParams.value || this.queryParams.selectValue)) return;
      this.queryFiltering.push({
        key: this.queryParams.key,
        value: this.queryParams.value || this.queryParams.selectValue,
        condition: this.queryParams.condition,
        index: this.queryFiltering.length + 1
      })
      this.initSessionKeyValue()
      this.changeQuery()
    },



    handleDeleteTag (row) {
      let index = this.queryFiltering.findIndex(item => item.index == row.index);
      if (index > -1) {
        this.queryFiltering.splice(index, 1)
      }
      this.changeQuery()
    },

    // 条件变化赋值
    changeQuery () {
      this.queryParams.sessionQueryConditionList = this.queryFiltering.map(item => {
        return {
          key: item.key,
          value: item.value,
          condition: item.condition,
        }
      })
      console.log('=== this.queryParams==', this.queryParams);
      this.getFlowMachlake()
    },


    getMoreParams (item) {
      console.log('🚀 val:', item)
    item.conditionList.forEach(items => {
      this.conditionItem[items] = this.conditionObj[items]
    });
      console.log('🚀this.conditionItem:', this.conditionItem)
      this.sessionKeyValue (item.key,item.type)
      this.selectType = item.type
      // this.sessionKeyValue('l7ProtocolId', 'select')
      // this.selectType = 'select'
    },


    // 根据值获取筛选值
    sessionKeyValue (key, type) {
      if (type == 'text') return;
      let params = {
        // TrafficArchiving  流量归档 TrafficRetrieval 流量检索(会话详情)
        capacity: 'TrafficRetrieval',
        key: key || '',
        pageIndex: 1,
        pageSize: 9999
      }
      sessionKeyValue(params).then(res => {
        if (res.code == 1) {
          if (!key) {
            this.sessionData = res.data.items
          } else {
            this.sessionSelectValue = res.data.items
          }
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },



    // 符号转换
    conditionText (val) {
      let str = ''
      switch (val) {
        case "eq": str = '='; break;
        case "ne": str = '!='; break;
        case "lt": str = '<'; break;
        case "le": str = '<='; break;
        case "gt": str = '>'; break;
        case "ge": str = '>='; break;
        case "like": str = 'like'; break;
        case "leftLike": str = 'left-like'; break;
        case "rightLike": str = 'right-like'; break;
        case "match": str = 'match'; break;
        default: str = val; break;
      }
      return str;
    },



    // 设置高度
    setStyle() {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = setTimeout(() => {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        this.fullHeight = window.fullHeight;
        this.fullWidth = window.fullWidth;
        this.contentHei = this.fullHeight - 36 - 50; // 80是头部高度  60是上下padding
        this.pageSize = Math.floor((this.contentHei - 167) / 96) || 1;
        // this.getReportList();
      }, 200);
    },
    // 返回详情
    returnCompany () {
      this.$router.push({
        path: '/hwDrillDetail',
        query: {
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page
        }
      });
    },

    // 返回列表
    returnCompanyList () {
      this.$router.push({
        path: '/hwDrill'
      });
    }
  }
};
</script>
<style scoped>
.packetAnalysis .input_value >>> .ivu-input {
  border-radius: unset !important;
}
.page_center {
  margin-top: 15px;
  text-align: center;
}
.targetHeader {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  margin: 15px 0px;
}
.targetHeader_left {
  margin: 15px 0px;
  /* border-right: 1px solid #999; */
  /* height: calc(100vh - 13vh); */
}
.page-wrap {
  padding: 25px;
}
.page-wrap-query /deep/ .ivu-cascader-rel .ivu-input {
  border-radius: 20px;
}
.reset-color /deep/ .ivu-select-selected-value {
  color: unset !important;
}
.page-content {
  background-color: #fff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}
.img-header {
  display: flex;
  /* justify-content: space-between; */
  padding: 20px 20px 0 20px;
  justify-content: flex-start;
  align-items: center;
}
.addressIcon {
  display: inline-block;
  height: 14px;
  width: 12px;
  background: url("../../../../assets/globalIcon/addressIcon.png") no-repeat
    center;
  background-size: 100% 100%;
  margin-bottom: -1px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.content-wrap {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 20px;
  flex: 1;
  height: 0;
}
</style>
<style scoped>
</style>
<style>
#app .page-wrap .targetHeader .condition_radius .ivu-select-selection {
  border-radius: 0px !important;
}
</style>
